<template>

  <div class="wrapper">
    <h1>体检预约-登录</h1>

    <section>
      <nav>
        <div :class="{ active: activeTab === 0 }" @click="setActiveTab(0)">密码登录</div>
        <div :class="{ active: activeTab === 1 }" @click="setActiveTab(1)">验证码登录</div>
      </nav>
      <div v-show="activeTab === 0">
        <div class="input-box">
          <font-awesome-icon :icon="['far', 'user']" style="color: #808080;position: relative; left: 2vw;" />
          <input type="text" v-model="user.userId" placeholder="输入手机号" style="position: relative; left: 2vw;" />
        </div>
        <div class="input-box">
          <font-awesome-icon icon="lock" style="color: #808080;position: relative; left: 2vw;" />
          <input type="password" v-model="user.password" placeholder="输入登录密码" style="position: relative; left: 2vw;" />
        </div>
        <div class="reg-box">
          <p @click="toRegister">注册</p>
          <p @click="forgetPassword">忘记密码？</p>
        </div>
        <div class="button-box" @click="login">登录</div>
      </div>
      <div v-show="activeTab === 1">
        <div class="input-box">
          <!--  <font-awesome-icon :icon="['far', 'user']" style="color: #808080;position: relative; left: 1vw;" /> -->
          <font-awesome-icon icon="phone" style="color: #808080;position: relative; left: 2vw;" />
          <input type="text" v-model="user.userId" placeholder="输入手机号" style="position: relative; left: 2.5vw;" />
        </div>
        <div class="code-container">
          <div class="code-box">
            <input type="code" v-model="user.code" placeholder="输入验证码" style="position: relative; left: 2.5vw;" />
          </div>
          <div class="p-box">
            <div class="reg-box">
              <p @click="countDown">{{ code.codeName }}</p>
            </div>
          </div>

        </div>
        <div class="button-box" @click="loginByCode">登录</div>
      </div>

    </section>
    <footer>
      <div>
        <div class="line"></div>
        <p>有疑问请联系客服</p>
        <div class="line"></div>
      </div>
      <p>4008-XXX-XXX</p>

    </footer>



    <el-dialog v-model="dialog1Visible" title="忘记密码" width="90%" :before-close="handleClose">
      <section style="width: 100%;">
        <div class="input-box">
          <font-awesome-icon icon="phone" style="color: #808080;position: relative; left: 2vw;" />
          <input type="text" v-model="forget.userId" placeholder="请输入注册的手机号"
            style="position: relative; left: 2.5vw;" />
        </div>
        <div class="code-container">
          <div class="code-box">
            <input type="code" v-model="forget.code" placeholder="请输入验证码" style="position: relative; left: 2.5vw;" />
          </div>
          <div class="p-box">
            <div class="reg-box">
              <p @click="countDown1">{{ code1.codeName }}</p>
            </div>
          </div>
        </div>
        <div class="button-box" @click="resetPassword">重置密码</div>
      </section>
    </el-dialog>

    <el-dialog v-model="dialog2Visible" title="重置密码" width="90%" :before-close="handleClose">
      <section style="width: 100%;">
        <div class="input-box">
          <input type="password" v-model="reset.newPass" placeholder="输入新的登录密码"
            style="position: relative; left: 2vw;" />
        </div>

        <div class="input-box">
          <input type="password" v-model="reset.confirmPass" placeholder="重新确认新的登录密码"
            style="position: relative; left: 2vw;" />
        </div>
        <div style="height: 5vw;">
          <p></p>
        </div>
        <div class="button-box" @click="savePassword">保存新密码</div>
      </section>
    </el-dialog>

  </div>
</template>


<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import axios from "../plugin/axiosInstance";
import { setSessionStorage,removeSessionStorage } from "../plugin/common.js";

const dialog1Visible = ref(false)
const dialog2Visible = ref(false)

const handleClose = (done: () => void) => {
  done();
}

const activeTab = ref(0);
const forget = reactive({
  userId: null,
  code: null
})

const reset = reactive({
  token: null,
  newPass: null,
  confirmPass: null
})


const forgetPassword = () => {
  dialog1Visible.value = true;
}

// 发送验证码获取修改密码的token
const resetPassword = () => {
  axios.post('/users/forgetPass', {
    userId: forget.userId,
    code: forget.code
  }).then(res => {
    if (res.data.code == 200) {
      dialog1Visible.value = false;
      dialog2Visible.value = true;
      reset.token = res.data.data;
      ElMessage({
        type: 'success',
        message: '请在5分钟之内完成修改!',
        customClass: 'my-message'
      })
    } else {
      ElMessage({
        type: 'error',
        message: res.data.msg,
        customClass: 'my-message'
      })
    }
  })
}

// 重置密码
const savePassword = () => {
  if (reset.newPass != reset.confirmPass) {
    ElMessage({
      type: 'error',
      message: '两次密码不一致!',
      customClass: 'my-message'
    })
    return;
  }
  axios.post('/users/resetPass', {
    token: reset.token,
    password: reset.confirmPass
  }).then(res => {
    if (res.data.code == 200) {
      dialog2Visible.value = false;
      ElMessage({
        type: 'success',
        message: '密码修改成功!',
        customClass: 'my-message'
      })
    } else {
      ElMessage({
        type: 'error',
        message: res.data.msg,
      })
    }
  });
}

const code = reactive({
  isSend: false,  //禁用
  codeName: "发送验证码",
  totalTime: 5 * 60, //一般是60
  timer: '', //定时器
})

const code1 = reactive({
  isSend: false,  //禁用
  codeName: "发送验证码",
  totalTime: 5 * 60, //一般是60
  timer: '', //定时器
})
const setActiveTab = (index) => {
  activeTab.value = index;
};

const router = useRouter();
const user = reactive({
  userId: '',
  password: '',
  code: ''
});


// 验证码倒计时
const countDown = () => {
  // 表单验证
  if (user.userId == '') {
    ElMessage({
      type: 'error',
      message: '手机号码不能为空！',
      customClass: 'my-message'
    })
    let el = document.querySelector('.my-message');
    if (el) el.style.cssText = '  border: 1px dashed blue;  min-width: 80%;'
    return;
  }
  if (code.isSend) return
  // code.getCode() // 获取验证码的接口
  code.isSend = true
  axios.get('/users/getCode/' + user.userId).then(res => {
    if (res.data.code == 200) {
      ElMessage({
        type: 'success',
        message: '验证码已发送,请注意查收',
        customClass: 'my-message'
      })
      let el = document.querySelector('.my-message');
      if (el) el.style.cssText = '  border: 1px dashed blue;  min-width: 80%;'
      code.codeName = code.totalTime + 's后重新发送'
      code.timer = setInterval(() => {
        code.totalTime--;
        code.codeName = code.totalTime + 's后重新发送';
        if (code.totalTime < 0) {
          clearInterval(code.timer)
          code.codeName = '重新发送验证码';
          code.totalTime = 5 * 60;
          code.isSend = false;
        }
      }, 1000)
    } else {
      ElMessage({
        type: 'error',
        message: res.data.msg,
        customClass: 'my-message'
      })
      let el = document.querySelector('.my-message');
      if (el) el.style.cssText = '  border: 1px dashed blue;  min-width: 80%;'
      code.isSend = false;
    }
  });
}

// 验证码倒计时-重置密码
const countDown1 = () => {
  // 表单验证
  if (forget.userId == '') {
    ElMessage({
      type: 'error',
      message: '手机号码不能为空！',
      customClass: 'my-message'
    })
    let el = document.querySelector('.my-message');
    if (el) el.style.cssText = '  border: 1px dashed blue;  min-width: 80%;'
    return;
  }
  if (code1.isSend) return;
  code1.isSend = true
  axios.get('/users/getCode/' + forget.userId).then(res => {
    if (res.data.code == 200) {
      ElMessage({
        type: 'success',
        message: '验证码已发送,请注意查收',
        customClass: 'my-message'
      })
      let el = document.querySelector('.my-message');
      if (el) el.style.cssText = '  border: 1px dashed blue;  min-width: 80%;'
      code1.codeName = code1.totalTime + 's后重新发送'
      code1.timer = setInterval(() => {
        code1.totalTime--;
        code1.codeName = code1.totalTime + 's后重新发送';
        if (code1.totalTime < 0) {
          clearInterval(code1.timer)
          code1.codeName = '重新发送验证码';
          code1.totalTime = 5 * 60;
          code1.isSend = false;
        }
      }, 1000)
    } else {
      ElMessage({
        type: 'error',
        message: res.data.msg,
        customClass: 'my-message'
      })
      let el = document.querySelector('.my-message');
      if (el) el.style.cssText = '  border: 1px dashed blue;  min-width: 80%;'
      code1.isSend = false;
    }
  });
}

const login = () => {
  // 表单验证
  if (user.userId == '') {
    ElMessage({
      type: 'error',
      message: '手机号码不能为空！',
      customClass: 'my-message'

    })
    let el = document.querySelector('.my-message');
    if (el) el.style.cssText = '  border: 1px dashed blue;  min-width: 80%;'
    return;
  }
  if (user.password == '') {
    ElMessage({
      type: 'error',
      message: '密码不能为空！',
      customClass: 'my-message'
    })
    let el = document.querySelector('.my-message');
    if (el) el.style.cssText = '  border: 1px dashed blue;  min-width: 80%;'
    return;
  }

  // 登录
  axios.post('users/login', user)  // json
    .then((response) => {
      if (response.data.code == 200) {
        let token = response.data.data;
        /* localStorage.setItem('token', token); */
        setSessionStorage('token', token);
        ElMessage({
          type: 'success',
          message: '登录成功,欢迎回来！',
          customClass: 'my-message'
        })
        let el = document.querySelector('.my-message');
        if (el) el.style.cssText = '  border: 1px dashed blue;  min-width: 80%;'
        setTimeout(() => {
          router.push('/index');
        }, 500);
      } else {
        ElMessage({
          type: 'error',
          message: '登录失败，请重试!',
          customClass: 'my-message'
        })
        let el = document.querySelector('.my-message');
        if (el) el.style.cssText = '  border: 1px dashed blue;  min-width: 80%;'
        removeSessionStorage('token');
      }
    });
}

const loginByCode = () => {
  if (user.userId == '') {
    ElMessage({
      type: 'error',
      message: '手机号码不能为空！',
      customClass: 'my-message'
    })
    let el = document.querySelector('.my-message');
    if (el) el.style.cssText = '  border: 1px dashed blue;  min-width: 80%;'
    return;
  }
  if (user.code == '') {
    ElMessage({
      type: 'error',
      message: '验证码不能为空！',
      customClass: 'my-message'
    })
    let el = document.querySelector('.my-message');
    if (el) el.style.cssText = '  border: 1px dashed blue;  min-width: 80%;'
    return;
  }

  axios.post('/users/loginByCode', { userId: user.userId, code: user.code }).then(res => {
    if (res.data.code == 200) {
      const token = res.data.data;
      setSessionStorage('token', token);
      ElMessage({
        type: 'success',
        message: '登录成功,欢迎回来!',
        customClass: 'my-message',
      })
      let el = document.querySelector('.my-message');
      if (el) el.style.cssText = '  border: 1px dashed blue;  min-width: 80%;'
      router.push('/index');
    } else {
      ElMessage({
        type: 'error',
        message: res.data.msg,
        customClass: 'my-message'
      })
      let el = document.querySelector('.my-message');
      if (el) el.style.cssText = '  border: 1px dashed blue;  min-width: 80%;'
      removeSessionStorage('token');
    }
  });
}

/* const setAlert = (title, type, description) => {
  alert.show = true;
  console.log('Alert shown:', alert.show); // 调试输出
  alert.title = title;
  alert.type = type;
  alert.description = description;
  setTimeout(() => {
    alert.show = false;
    console.log('Alert hidden:', alert.show); // 调试输出
  }, 2000);
} */

const toRegister = () => {
  router.push('/register');
}
</script>

<style scoped>
@import '@/assets/css/login.css';

nav {
  display: flex;
  justify-content: center;
  border-bottom: 2px solid #ddd;
}

nav div {
  padding: 10px 20px;
  cursor: pointer;
  transition: background-color 0.3s, color 0.3s;
}

nav div.active {
  background-color: #007bff;
  color: white;
  border-bottom: 2px solid #007bff;
}

nav div:not(.active):hover {
  background-color: #f0f0f0;
}

nav div:first-child {
  border-right: 1px solid #ddd;
}

:deep(.my-message) {
  min-width: 600px !important;
}
</style>